package com.ruleengine.admin.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.ruleengine.util.exception.RuleEngineException;

/**
 * @author lianghanwei on 2024/3/27
 */
@ControllerAdvice
public class GlobalExceptionConfig {

    private static final String ERROR_MESSAGE_RESP_KEY = "errorMsg";

    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({RuleEngineException.class, Exception.class})
    public Map<String, String> ruleEngineExceptionHandler(Exception e){
        Map<String, String> map = new HashMap<>();

        map.put(ERROR_MESSAGE_RESP_KEY, e.getMessage());

        return map;
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map<String, String> validationExceptionHandler(MethodArgumentNotValidException ex) {
        // @Valid 若出现校验错误，抛出 MethodArgumentNotValidException
        // @Validated 若出现校验错误，抛出 ConstraintViolationException
        Map<String, String> errors = new HashMap<>();

        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        return errors;
    }

}
